/**
 * 
 */

package com.pp.admin.common.server.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.pp.admin.common.client.beans.BaseDomain;
import com.pp.admin.common.client.exceptions.InvalidDomain;
import com.pp.admin.common.client.service.DomainService;
import com.pp.admin.common.server.PersistenceManagerFactory;
import com.pp.admin.common.server.entities.User;
import com.pp.admin.common.server.entities.UsersDomain;

/**
 * @author pandurang
 */
public class DomainServiceImpl extends BaseAdminService implements DomainService {
	
	/**
	 * 
	 */
	private static final long	serialVersionUID	= 3331581790295343640L;
	
	/*
	 * (non-Javadoc)
	 * @see com.pp.admin.common.client.service.DomainService#getDomainByDomainID(java.lang.String)
	 */
	@SuppressWarnings( "unchecked" )
	@Override
	public BaseDomain getDomainByDomainID( String domainID ) throws InvalidDomain {

		return super.getDomainEntityByDomainID( domainID ).exportBaseDomain();
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.pp.admin.common.client.service.DomainService#getDomainsByUserID(java.lang.String)
	 */
	@SuppressWarnings( "unchecked" )
	@Override
	public List<com.pp.admin.common.client.beans.Domain> getDomainsByUserID( String userID ) {

		List<com.pp.admin.common.client.beans.Domain> listUserDomains = new ArrayList<com.pp.admin.common.client.beans.Domain>();
		PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager();
		try {
			Query query = pm.newQuery( UsersDomain.class );
			query.setFilter( FLD_USR_DOMN_USER_KEY + " == " + FLD_USR_DOMN_USER_KEY + QUERY_PARAM );
			query.declareParameters( Key.class.getName() + " " + FLD_USR_DOMN_USER_KEY + QUERY_PARAM );
			
			List<UsersDomain> list = (List<UsersDomain>) query.execute( User.generateKey( userID ) );
			for ( UsersDomain usersDomain : list ) {
				listUserDomains.add( usersDomain.getDomain().export() );
			}
			
		} finally {
			PersistenceManagerFactory.closePersistenceManager();
		}
		return listUserDomains;
	}
}
